package com.roc.template.activiti.controller;

import com.roc.template.activiti.dto.HistoryProcess;
import com.roc.template.activiti.dto.LeaveTask;
import com.roc.template.activiti.dto.Process;
import com.roc.template.mongo.model.LeaveApply;
import com.roc.template.mongo.service.LeaveService;
import com.roc.template.base.BaseController;
import com.roc.template.base.PageBean;
import com.roc.template.base.Result;
import com.roc.template.base.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ActivitiController
 * @Description: TODO
 * @Author Administrator
 * @Date 2020/8/10 09 43
 * @Version V1.0
 **/
@Api(description = "activiti基本操作")
@RestController
@RequestMapping("/activiti")
public class ActivitiController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RepositoryService repositoryService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private LeaveService leaveService;

    @Resource
    private HistoryService historyService;

    @ApiOperation("发布流程")
    @GetMapping("/deployProcess")
    @ResponseBody
    public Result deploy() {
//        BpmnModel bpmnModel = ProcessUtils.genarateBpmnModel();
        Deployment deployment = repositoryService.createDeployment()
                .addClasspathResource("processes/leave.bpmn")
//                .addClasspathResource("processes/leave.png")
//                .addBpmnModel("test.bpmn",bpmnModel)
                .deploy();
        logger.info("部署ID："+deployment.getId());
        logger.info("部署名称："+deployment.getName());
        return new Result(true,"","","");
    }

    @ApiOperation("删除流程")
    @GetMapping("/deletedeploy")
    @ResponseBody
    public Result deletedeploy(@RequestParam("deployid") String deployid) {
        repositoryService.deleteDeployment(deployid,true);
        return new Result(true,"","","");
    }

    @ApiOperation("获取流程列表")
    @GetMapping("/getProcessList")
    @ResponseBody
    public Result getProcessList(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        int firstrow = (pageNum - 1) * pageSize;
        List<ProcessDefinition> processDefinitions = repositoryService.createProcessDefinitionQuery()
                .listPage(firstrow, pageSize);
        int total = repositoryService.createProcessDefinitionQuery().list().size();

        List<Process> mylist = new ArrayList<Process>();
        for (int i = 0; i < processDefinitions.size(); i++) {
            Process p = new Process();
            p.setDeploymentId(processDefinitions.get(i).getDeploymentId());
            p.setId(processDefinitions.get(i).getId());
            p.setKey(processDefinitions.get(i).getKey());
            p.setName(processDefinitions.get(i).getName());
            p.setResourceName(processDefinitions.get(i).getResourceName());
            p.setDiagramresourcename(processDefinitions.get(i).getDiagramResourceName());
            mylist.add(p);
        }
        PageBean<Process> processPageBean = new PageBean<>(mylist, pageNum, pageSize, total);

        return new Result(true,"","",processPageBean);
    }


    @ApiOperation("启动流程并分配人员")
    @PostMapping(value = "/startleave")
    @ResponseBody
    public Result start_leave(@RequestBody LeaveApply apply, HttpServletRequest request) throws Exception {
        UserVo userInfo = getUserInfo(request);
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("apply", userInfo.getOpenId());
        variables.put("manage", userInfo.getOpenId());
        variables.put("leader", userInfo.getOpenId());
        variables.put("hr", userInfo.getOpenId());
        ProcessInstance ins = leaveService.startWorkflow(apply, userInfo.getOpenId(), variables);
        logger.info("流程id" + ins.getId() + "已启动");
        return new Result(true,"","","");
    }

    @ApiOperation("获取待办列表")
    @PostMapping(value = "/getMyTask")
    @ResponseBody
    public Result deptTaskList(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, HttpServletRequest request) throws Exception {
        UserVo userInfo = getUserInfo(request);
        String openId = userInfo.getOpenId();
        pageNum = (pageNum - 1) * pageSize;
        PageBean<LeaveTask> myTaskList = leaveService.getMyTaskList(openId, pageNum, pageSize);
        return new Result(true,"","",myTaskList);
    }

    @ApiOperation("查看流程")
    @PostMapping(value = "/dealtask")
    @ResponseBody
    public Result dealtask(String taskid) {
        Task task = taskService.createTaskQuery().taskId(taskid).singleResult();
        if(task==null) {
            new Result(false,"流程已结束","-1","");
        }
        ProcessInstance process = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId())
                .singleResult();
        LeaveApply leave = leaveService.queryById(process.getBusinessKey());
        return new Result(true,"","",leave);
    }

    @ApiOperation("完成流程")
    @PostMapping(value = "/task/deptcomplete")
    @ResponseBody
    public Result deptcomplete(String taskid, HttpServletRequest request) throws Exception {
        UserVo userInfo = getUserInfo(request);
        String openId = userInfo.getOpenId();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("day", 3);
        taskService.claim(taskid, openId);
        taskService.complete(taskid, variables);
        return new Result(true,"","","");
    }


    @ApiOperation("流程历史记录")
    @PostMapping(value = "/getAllHistory")
    @ResponseBody
    public Result getAllHistory(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize, HttpServletRequest request) throws Exception {
        UserVo userInfo = getUserInfo(request);
        String openId = userInfo.getOpenId();
        pageNum = (pageNum - 1) * pageSize;

        PageBean<HistoryProcess> myTaskList = leaveService.getHistory(openId, pageNum, pageSize);
        return new Result(true,"","",myTaskList);
    }



    @ApiOperation("单个流程历史记录")
    @PostMapping(value = "/getInstantIdHistory")
    @ResponseBody
    public Result getInstantIdHistory(@RequestParam("instanceid") String instanceid) {

        List<HistoricActivityInstance> his = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceid).orderByHistoricActivityInstanceStartTime().asc().list();
        return new Result(true,"","",his);
    }
}
